use crate::rtmp::session::server_session;
use commonlib::auth::Auth;
use failure::Error;
use std::net::SocketAddr;
use streamhub::define::StreamHubEventSender;
use tokio::net::TcpListener;

mod config;

mod chunk;

mod cache;
mod handshake;
mod messages;

mod net_connection;

mod net_stream;

mod protocol_control_messages;
pub mod relay;
mod session;
mod user_control_messages;
mod utils;

// RTMP 服务器
pub struct RtmpServer {
    // 服务器监听地址
    address: String,
    // 事件发送器，用于发送流相关事件
    event_producer: StreamHubEventSender,
    // Group of Pictrues，用于控制关键帧间隔
    gop_num: usize,
    // 认证消息（可选）
    auth: Option<Auth>,
}

impl RtmpServer {
    pub fn new(
        address: String,
        event_producer: StreamHubEventSender,
        gop_num: usize,
        auth: Option<Auth>,
    ) -> Self {
        Self {
            address,
            event_producer,
            gop_num,
            auth,
        }
    }

    // 启动服务器
    pub async fn start(&mut self) -> Result<(), Error> {
        // 解析监听地址
        let socket_addr: &SocketAddr = &self.address.parse()?;
        let listener = TcpListener::bind(socket_addr).await?;
        log::info!("Rtmp Server listening on {}", socket_addr);

        loop {
            // 接收连接
            let (tcp_stream, _) = listener.accept().await?;

            // 创建一个新的服务器会话
            let mut session = server_session::ServerSession::new(
                tcp_stream,
                self.event_producer.clone(),
                self.gop_num,
                self.auth.clone(),
            );

            // 使用 tokio::spawn 异步运行会话
            tokio::spawn(async move {
                if let Err(err) = session.run().await {
                    // 如果会话运行出错，记录错误日志
                    log::error!(
                        "Session execution error: session_type: {}, app_name: {}, stream_name: {}, err: {}",
                        // 会话类型
                        session.common.session_type,
                        // 应用名称
                        session.app_name,
                        // 流名称
                        session.stream_name,
                        // 错误信息
                        err
                    );
                }
            });
        }
    }
}
